package com.example.demojava.service.impl;

import com.example.demojava.entity.Sample;
import com.example.demojava.repository.SampleRepository;
import com.example.demojava.service.SampleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SampleServiceImpl implements SampleService {

    @Autowired
    private SampleRepository sampleRepository;

    @Override
    @Transactional
    public Sample createSample(Sample sample) {
        if (sampleRepository.existsByCode(sample.getCode())) {
            throw new RuntimeException("样本编号已存在");
        }
        return sampleRepository.save(sample);
    }

    @Override
    public Page<Sample> findAll(Pageable pageable) {
        return sampleRepository.findAll(pageable);
    }

    @Override
    public Sample findById(Long id) {
        return sampleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("样本不存在"));
    }

    @Override
    @Transactional
    public Sample updateSample(Long id, Sample sample) {
        Sample existingSample = findById(id);
        existingSample.setName(sample.getName());
        existingSample.setFileName(sample.getFileName());
        return sampleRepository.save(existingSample);
    }

    @Override
    @Transactional
    public void deleteSample(Long id) {
        sampleRepository.deleteById(id);
    }
}